from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.orders.models import *
from apps.meiduo_admin.utils import UserDefinePagination
from ..serializers.order import *


class OrdersViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSerializer
    pagination_class = UserDefinePagination

    # 不需要删除方法 重写删除方法
    def destroy(self, request, *args, **kwargs):
        return Response({
            "IP": self.request.META['REMOTE_ADDR']
        }, status=403)

    # 修改订单状态 单独对订单的某个字段操作 增加额外的方法 使用装饰器 action
    @action(methods=["PUT"], detail=True)
    def status(self, request, pk):

        # 参数获取
        status = request.data.get("status")
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except Exception as e:
            raise serializers.ValidationError("订单不存在")
        order.status = status
        order.save()
        return Response({
            "order_id": order.order_id,
            "status": order.status
        })
